<?php

/* username and password  */
if ($_POST['username'] != NULL) {
    $username = $_POST['username'];
    if ($_POST['pass'] != NULL) {
        $pwd = $_POST['pass'];

        /* Connect to database, in this case, connect to localhost  */
        include_once('conf/dbconfig.php');
        $cfg = new dbconfig();
        $host = $cfg->get_dbhost();
        $db = $cfg->get_dbname();
        $usr = $cfg->get_dbusername();
        $pass = $cfg->get_dbpwd();
        $connection = pg_connect("host = $host dbname = $db user = $usr password = $pass")
                or die("Không kết nối được đến server: " . pg_last_error());

        /* queries to identify user  */
        /* check user is admin or normal user */
        $query_ad = "SELECT * FROM admin WHERE (username = '$username') AND (password = '$pwd')";
        $check = pg_query($connection, $query_ad);
        if (pg_num_rows($check) > 0) {
            setcookie('admin', $username, COOKIE_EXP_TIME);
            $_SESSION['admin'] = true;
            $_SESSION['user'] = $username;
        } else {
            $query_login = "SELECT * FROM customer WHERE (username = '$username') AND (password = '$pwd')";
            $check = pg_query($connection, $query_login);
            if (pg_num_rows($check) > 0) {
                setcookie('user', $username, COOKIE_EXP_TIME);
                $_SESSION['user'] = $username;
            }
        }
        pg_free_result($check);
        pg_close();
    }
}
?>